import style from './index.module.css';
import React, { useEffect, useState } from 'react'
import { Button, Input, Table, Space, Modal, Form, Upload, message, Image, Select, Row, Col } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { addDish, addFlavor, getDishCategoryList, getDishList, getFlavorList, getFlavorByDishId, deleteDish, updateDish } from '@/redux/home/rightPages/DishManagement/DishManagement';
import { upLoadFile } from '@/redux/common/fileMangement';
import MutipleInput from '@/components/MutipleInput';
const { Option } = Select;


export default function DishManagement() {
  const [visible, setVisible] = useState(false);

  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState(null);

  const [flavorVisible, setFlavorVisible] = useState();
  const [form] = Form.useForm();
  const [flavorForm] = Form.useForm();
  const [searchForm] = Form.useForm();
  const [dishCategoryList, setDishCategoryList] = useState([]);

  const [flavorList, setFlavorList] = useState([]);
  const [dishList, setDishList] = useState([]);

  const [operatorType, setOperatorType] = useState('add');

  const columns = [
    {
      title: 'id',
      dataIndex: 'id',
      key: 'id',
      hidden: true, // 隐藏该列
    },
    {
      title: '菜品名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '图片',
      dataIndex: 'image',
      key: 'image',
    },
    {
      title: '菜品分类',
      dataIndex: 'category',
      key: 'category',
    },
    {
      title: '售价',
      dataIndex: 'price',
      key: 'price',
    },
    {
      title: '售卖状态',
      dataIndex: 'status',
      key: 'status'
    },
    {
      title: '最后操作时间',
      dataIndex: 'updateDateTime',
      key: 'updateDateTime'
    },
    {
      title: '操作',
      key: 'action',
      render: (text, record) => (
        <Space size="middle">
          <a onClick={() => handleModify(record)}>修改 </a>
          <a onClick={() => handleDelete(record.id)}>删除</a>
          <a onClick={() => discontinued(record.id)}>停售</a>
        </Space>
      ),
    },
  ].filter(column => !column.hidden)

  useEffect(() => {
    getDishCategory();
    getDish();
    getFlavor();
  }, [])
  function getDishCategory() {
    getDishCategoryList().then(res => {
      setDishCategoryList(res.data.resultData);
    })
  }

  const handleModify = async (record) => {


    const res = await getFlavorByDishId(record.id);
    if (res.data.resultCode === 200) {

      record.flavor = res.data.resultData;
    }
    form.setFieldsValue({
      id: record.id,
      name: record.name,
      category: record.category,
      price: record.price,
      description: record.description,
      imageId: record.image,
    });
    if (record.flavor) {
      flavorForm.setFieldsValue({
        flavorName1: record.flavor.name,
        flavorTag1: record.flavor.value.split(","),
      });
    }
    setOperatorType('modify');
    setVisible(true)
  }

  const handleDelete = (dishId) => {
    deleteDish(dishId).then(res => {
      if (res.data.resultCode === 200) {
        message.success('删除成功');
        getDish();
      } else {
        message.error(res.data.resultMessage);
      }
    }
    )
  }
  function getFlavor() {
    getFlavorList().then(res => {
      setFlavorList(res.data.resultData);
    })
  }

  function getDish() {
    getDishList().then(res => {
      if (res.data.resultCode === 200) {
        setDishList(res.data.resultData);
      }
    })
  }

  function discontinued(dishId) {
    const dish = {
      id: dishId,
      status: 1,
    }
    updateDish(dish).then(res => {
      if (res.data.resultCode === 200) {
        message.success('停售成功');
        getDish();
      } else {
        message.error(res.data.resultMessage);
      }
    })
  }

  function getDishFlavor(dishId) {
    getFlavorByDishId(dishId).then(res => {
      if (res.data.resultCode === 200) {

      }
    })
  }

  const handleClick = () => {
    setVisible(true);
    setOperatorType('add');
  }

  const customRequest = async ({ file, onSuccess, onError }) => {
    try {
      setLoading(true);
      const response = await upLoadFile(file);
      onSuccess(response, file);
      console.log(response);
      form.setFieldsValue({
        imageId: response.data.resultData,
      });


      // 获取预览图
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => setImageUrl(reader.result);
    } catch (error) {
      onError(error);
      message.error(error.message);
    } finally {
      setLoading(false);
    }
  };


  function beforeUpload(file) {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('只能上传 JPG/PNG 文件!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片大小不能超过 2MB!');
    }
    return isJpgOrPng && isLt2M;
  }




  const handleOnSave = () => {
    form.validateFields().then(values => {
      const param = {
        name: values.name,
        category: values.category,
        flavor: {
          name: values.flavorName1,
          value: String(values.flavorTag1),
        },
        price: values.price,
        description: values.description,
        image: values.imageId,
      }

      addDish(param).then(res => {
        const { data } = res;
        if (data.resultCode === 200) {
          message.success('保存成功');
          form.resetFields();
          setVisible(false);
          getDish();
        } else {
          message.error(data.resultMessage);
        }
      });
    });
  }

  const handleOnSaveAndKeepAdding = () => {
    form.validateFields().then(values => {
      addDish(values).then(res => {
        const { data } = res;
        if (data.resultCode === 200) {
          message.success('保存成功');
          form.resetFields();
        } else {
          message.error(data.resultMessage);
        }
      });
    });

  }
  const handleOnCancel = () => {
    setVisible(false);
  }

  const handleaddFlavor = () => {
    setFlavorVisible(true);

  }

  const handleFlavorSave = () => {
    flavorForm.validateFields().then(values => {
      addFlavor(values).then(res => {
        if (res.data.resultCode === 200) {
          message.success('保存成功');
          flavorForm.resetFields();
          setFlavorVisible(false);
          getFlavor();
        } else {
          message.error(res.data.resultMessage);
        }
      });
    });
  }

  const handleFlavorCancel = () => {
    flavorForm.resetFields();
    setFlavorVisible(false);
  }

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>请上传菜品图片</div>
    </div>
  )
  const handleSearchClick = () => {
    searchForm.validateFields().then(values => {
      getDishList(values).then(res => {
        if (res.data.resultCode === 200) {
          setDishList(res.data.resultData);
        }
      })
    })
  }

  return (
    <div className={style.container}>
      <div className={style.card}>
        <div className={style.cardContent}>

          <div className={style.firstLine}>
            <Form layout="inline"
              form={searchForm}>
              <Row gutter={2}>
                <Col>
                  <Form.Item label="菜品名称" name="name">
                    <Input className={style.input} />
                  </Form.Item>
                </Col>
                <Col>
                  <Form.Item label="菜品分类" name="category">
                    <Input className={style.input} />
                  </Form.Item>
                </Col>
                <Col>
                  <Form.Item label="售卖状态" name="status">
                    <Input className={style.input} />
                  </Form.Item>
                </Col>
                <Col>
                  <Button className={style.search} onClick={handleSearchClick}>查询</Button>
                </Col>
                <Col>
                  <Button className={style.batchDelete}>批量删除</Button>
                </Col>
                <Col>
                  <Button className={style.add} onClick={handleClick}>+新建菜品</Button>
                </Col>
              </Row>
            </Form>

          </div>
          <div className={style.tableContainer}>
            <Table columns={columns} dataSource={dishList}>

            </Table>
          </div>
        </div>
      </div>
      <Modal
        title="新建菜品"
        visible={visible}
        onCancel={() => {
          setVisible(false)
          setOperatorType('add')
        }}
        footer={null}
        width={800}

      >
        <Form labelCol={{ span: 4 }} // 标签占据 6 列
          wrapperCol={{ span: 20 }}
          form={form}
        >

          <Form.Item
            name="id"
            label="id"
            noStyle
          >
          </Form.Item>
          <Form.Item
            name="name"
            label="菜品名称"
            rules={[
              { required: true },
            ]}

          >
            <Input className={style.dishInput} />
          </Form.Item>
          <Form.Item
            name="category"
            label="菜品分类"
            rules={[
              { required: true },
            ]}
          >
            <Select className={style.dishInput}>
              {dishCategoryList.length > 0 ? (
                dishCategoryList.map(item => <Option key={item.id} value={item.name}>{item.name}</Option>)
              ) : (
                <Option value="" disabled>暂无选项</Option>
              )}
            </Select>
          </Form.Item>
          <Form.Item
            name="price"
            label="菜品价格"
            rules={[
              { required: true },
            ]}
          >
            <Input className={style.dishInput} />
          </Form.Item>
          <Form.Item
            name="flavorRecipeConfiguration"
            label="口味做法配置"

          >
            <div className={style.flavorRecipeConfigurationContainer}>
              <div className={style.left}>
                <div>口味名（三个字内）</div>
                <Form.Item name="flavorName1"
                  noStyle
                  rules={[
                    { required: true },
                  ]}>
                  <Select > {flavorList.length > 0 ? (
                    flavorList.map(item => <Option key={item.id} value={item.name}>{item.name}</Option>)
                  ) : (
                    <Option value="" disabled>暂无选项</Option>
                  )}
                  </Select >
                </Form.Item>
                <Form.Item name="flavorName2" noStyle>
                  <Select > {flavorList.length > 0 ? (
                    flavorList.map(item => <Option key={item.id} value={item.name}>{item.name}</Option>)
                  ) : (
                    <Option value="" disabled>暂无选项</Option>
                  )}
                  </Select >
                </Form.Item>

              </div>
              <div className={style.right}>
                <div>口味标签（输入后，回车添加)</div>
                <Form.Item name="flavorTag1" noStyle>
                  <MutipleInput />
                </Form.Item>
                <Form.Item name="flavorTag2" noStyle>
                  <MutipleInput />
                </Form.Item>
              </div>
            </div>

            <Button className={style.addedMenuCategories} onClick={handleaddFlavor}>添加口味</Button>
          </Form.Item>
          <Form.Item
            name="image"
            label="菜品图片"
            rules={[
              { required: true },
            ]}
          >
            <Upload
              name="avatar"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              customRequest={customRequest}
              beforeUpload={beforeUpload}
            >
              {imageUrl ? (
                <Image
                  src={imageUrl}
                  alt="avatar"
                  style={{ width: '100%', height: '100%' }}
                  preview={false}
                />
              ) : (
                uploadButton
              )}
            </Upload>
          </Form.Item>
          <Form.Item name="imageId" style={{ display: 'none' }} />
          <Form.Item
            name="description"
            label="菜品描述"
          >
            <Input className={style.describeInput}
              placeholder='请输入菜品描述' />
          </Form.Item>
        </Form>
        <Row gutter={5} type="flex" align="middle" justify="center">
          <Col><Button onClick={handleOnSave}>保存</Button></Col>
          {
            operatorType === 'add' && (
              <Col>
                <Button onClick={handleOnSaveAndKeepAdding}>保存并继续添加菜品</Button>
              </Col>
            )
          }
          <Col><Button onClick={handleOnCancel}>退出</Button></Col>
        </Row>
      </Modal>

      <Modal
        title="新增口味"
        visible={flavorVisible}
        onCancel={() => setFlavorVisible(false)}
        footer={null}
        width={800}

      >
        <Form labelCol={{ span: 4 }} // 标签占据 6 列
          wrapperCol={{ span: 20 }}
          form={flavorForm}
        >

          <Form.Item
            name="name"
            label="口味名"
            rules={[
              { required: true },
            ]}

          >
            <Input className={style.dishInput} />
          </Form.Item>
        </Form>
        <Row gutter={5} type="flex" align="middle" justify="center">
          <Col><Button onClick={handleFlavorSave}>保存</Button></Col>
          <Col><Button onClick={handleFlavorCancel}>退出</Button></Col>
        </Row>
      </Modal>
    </div>
  )
}

